package com.hwy.chart.coordinate.axis

import android.graphics.Canvas
import android.graphics.RectF
import kotlin.math.max
import kotlin.math.min

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/10 18:52
 * 说明: 通用的X轴
 * =======================================
 */
open class ChartXAxis<T> : BaseAxis<T>() {

    /**
     * 曲线绘制的偏移量
     * 例如：坐标总长度为 100，[dataOffset] = 10，则表示当前曲线只绘制了10个点
     */
    var dataOffset = 0

    override fun initAxis() {
        orientation = HORIZONTAL
    }

    override fun calculateCoordinate(bounds: RectF): Float {
        return bounds.bottom - axisWidth / 2F - (bounds.height() - axisWidth) * axisSite
    }

    override fun drawAxis(canvas: Canvas, bounds: RectF) {
        if (axisWidth < 0F) {
            return
        }
        axisPaint.run {
            color = axisColor
            strokeWidth = axisWidth
        }
        // 计算横轴显示的y坐标
        val yCoordinate = calculateCoordinate(bounds)
        canvas.drawLine(bounds.left, yCoordinate, bounds.right, yCoordinate, axisPaint)
    }

    override fun getIndexByCoordinate(coordinate: Float?, bounds: RectF): Int? {
        return coordinate?.let {
            dataList.run {
                // 阈值校验
                var realCoordinate = max(coordinate, bounds.left)
                realCoordinate = min(realCoordinate, bounds.right)
                // 转换屏幕位置为图表中的坐标位置
                var chartCoordinate = realCoordinate - bounds.left
                // 根据百分比计算对应的index
                (chartCoordinate / bounds.width() * (size - 1) + 0.5F).toInt()
            }
        }

    }

    override fun getCoordinateByIndex(index: Int, bounds: RectF): Float? {
        return dataList?.run {
            val step = bounds.width() / (size - 1)
            bounds.left + step * index
        }
    }

}